#include "head.h"

int analyze_cmd(int net_fd)
{
    // 登录
    request_t *request = (request_t*)malloc(sizeof(request_t));

    int exit = 0;
    while (1)
    {
        // memset(request->args, 0, sizeof(request->args));
        // int ret = recv(net_fd, request, sizeof(request_t), 0);
        // printf("flag = %d\n", request->flag);

        memset(request, 0, sizeof(request_t));
        printf("等待客户端发报文\n");
        int ret = recv(net_fd, request, sizeof(request_t), 0);
        if (ret == 0) {
            printf("客户端断开连接\n");
            break;
        }
        printf("---请求报文---\n");
        printf("flag: %d\n",request->flag);
        printf("user_name: %s\n",request->user_name);
        printf("args: %s\n",request->args);
        printf("path: %s\n",request->path);
        printf("-------------\n");

        // 接收的是空报文，对方可能已经错误断开
        exit = gotodo(request, net_fd);
        if(exit == 1){
            break;
        }
    }

    free(request);
    close(net_fd);
    return 0;
}

int gotodo(request_t *request, int net_fd)
{
    switch (request->flag)
    {
    case LOGIN:
        // 登录函数
        login(request, net_fd);
        break;
    case CD:
        net_cd(request, net_fd);
        break;
    case LS:
        net_ls(request, net_fd);
        break;
    case PUTS:
        net_puts(request, net_fd);
        break;
    case GETS:
        net_gets(request, net_fd);
        break;
    case RM:
        net_rm(request, net_fd);
        break;
    case PWD:
        net_pwd(request, net_fd);
        break;
    case MKDIR:
        net_mkdir(request, net_fd);
        break;
    case EXIT:
        return 1;
    default:
        break;
    }
    return 0;
}

int login(request_t *request, int net_fd)
{
    char user_name[60];
    strcpy(user_name, request->user_name);

    response_t response;
    memset(&response, 0, sizeof(response_t));
    
    if (access(user_name, F_OK) == 0)
    {
        // 用户存在,返回登录成功消息
        strcpy(response.args, "登录成功");
        LOG(INFO, user_name, "login", "login success");
        response.status = 0;
    }
    else
    {
        // 用户不存在，创建对应的文件夹，返回对应消息
        int ret = mkdir(user_name, 0755);
        if (ret == -1)
        {
            strcpy(response.args, "创建新用户失败");
            LOG(ERROR, user_name, "login", "login failed");
            // 创建失败，返回注册失败信息
            response.status = 1;
        }
        else
        {
            strcpy(response.args, "新用户注册");
            LOG(INFO, user_name, "login", "register and login success");
            response.status = 0;
        }
    }
    
    // 回传结构体
    send(net_fd, &response, sizeof(response_t), 0);
    return 0;
}
